<template>
  <div class="login">
    <div class="login_box">
      <div class="img_box">
        <img src="../assets/img.jpg"
             alt="">
      </div>
      <el-form label-width="0px"
               class="form_box"
               :model="form"
               :rules="loginFormRules"
               ref="loginFormRefs">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-s-custom"
                    v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock"
                    v-model="form.password"
                    type="show-password"></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary"
                     @click="onSubmit">登陆</el-button>
          <el-button type="info"
                     @click="restLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      form: {
        username: 'admin',
        password: '123456'
      },
      loginFormRules: {
        // 验证用户名
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在3-5个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3-5个字符', trigger: 'blur' }]
      }
    }
  },
  methods: {
    onSubmit () {
      this.$refs.loginFormRefs.validate(async valid => {
        // 验证表单是否正确
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('login', this.form)
        if (res.meta.status !== 200) {
          return this.$message.error('登录失败')
        }
        this.$message({
          showClose: true,
          message: '登陆成功',
          type: 'success'
        })
        window.sessionStorage.setItem('token', res.data.token)

        this.$router.push('/home')
      })
    },
    restLoginForm () {
      this.$refs.loginFormRefs.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  background-image: url(../assets/img.jpg);
  color: white;
  height: 100%;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
  box-shadow: 0 0 10px slategray;
}

.img_box img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  position: absolute;
  right: 50%;
  transform: translate(50%, -50%);
  padding: 10px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  background-color: white;
}
.btns {
  display: flex;
  justify-content: center;
}
.form_box {
  position: absolute;
  width: 100%;
  box-sizing: border-box;
  bottom: 0%;
  padding: 0 20px;
}
</style>
